import { Input, NavBar, TextArea } from 'antd-mobile';
import { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';

import styles from './EditInput.module.scss';

type Props = {
  onClose: (value: string, prop: string) => void;
  prop: string;
  value: string;
  onValueChange: (value: string, prop: string) => void;
};

export const EditInput = (props: Props) => {
  const history = useHistory();

  // 昵称编辑组件的状态
  // console.log('props.value', props.value);
  const [value, setValue] = useState(props.value);
  // console.log('use state value', value);

  // 组件渲染完毕后，检查props.value是否发生变化
  // useEffect(() => {
  //   setValue(props.value);
  // }, [props.value]);

  return (
    <div className={styles.root}>
      <NavBar
        onBack={() => {
          props.onClose(value, props.prop);
        }}
        className="navbar"
        right={
          <span
            className="commit-btn"
            onClick={() => props.onValueChange(value, props.prop)}
          >
            提交
          </span>
        }
      >
        {props.prop === 'name' ? '编辑昵称' : '编辑简介'}
      </NavBar>

      <div className="edit-input-content">
        <h3>{props.prop === 'name' ? '昵称' : '简介'}</h3>
        {props.prop === 'name' ? (
          <div className="input-wrap">
            <Input
              value={value}
              onChange={setValue}
              // 下面的写法和上面的等价
              // onChange={(value) => {
              //   console.log(value);
              //   setName(value);
              // }}
              placeholder="请输入"
            />
          </div>
        ) : (
          <TextArea
            className="textarea"
            value={value ? value : ''}
            onChange={setValue}
            placeholder="请输入"
            maxLength={100}
            rows={4}
            showCount
          />
        )}
      </div>
    </div>
  );
};
